

#import "signViewController.h"
#define DefaultLocationTimeout  6
#define DefaultReGeocodeTimeout 3

@interface signViewController ()<MAMapViewDelegate, AMapLocationManagerDelegate>
@property (nonatomic, copy) AMapLocatingCompletionBlock completionBlock;
@end

@implementation signViewController
//全局变量
{
    NSMutableDictionary *_eventsByDate;
    NSMutableDictionary *_ByDate;
    
    NSMutableArray *_datesSelected;
    NSMutableArray *_datesLeaveOK;
    NSMutableArray *_datesLeaveNO;
    BOOL _selectionMode;
    NSString *sign_address;
    NSString *sign_location;
}
//重写init
-(instancetype)init{
    self = [super init];
    if (self)
    {
        [self setToptittle:@"签到"];
        [self setTopTittleColor:[UIColor whiteColor]];
        [self setTopBgColor:headColor];
        [self setBackBtnImage:[UIImage imageNamed:@"wo_merchandise_detail_back@3x"]];
        [self setBackBtnHide:NO];
    }
    return self;
}
//主函数
- (void)viewDidLoad {
    [super viewDidLoad];
    sign_address=@"";
    sign_location=@"";
    
    _eventsByDate = [NSMutableDictionary new];
    
    [self createEvents];
    
    [self makeLoading];
    
    [self MapDidLoad];    
}

#pragma mark - CalendarManager delegate

//日历协议
//日历刷新时循环此函数
- (void)calendar:(JTCalendarManager *)calendar prepareDayView:(JTCalendarDayView *)dayView
{
    dayView.hidden = NO;
    // Hide if from another month
    if([dayView isFromAnotherMonth]){
        dayView.hidden = YES;
    }
    // Today
    if([_calendarManager.dateHelper date:[NSDate date] isTheSameDayThan:dayView.date]){
        dayView.circleView.hidden = NO;
        dayView.circleView.backgroundColor = xdGrayColor;
        //dayView.dotView.backgroundColor = [UIColor blackColor];
        dayView.textLabel.textColor = [UIColor blackColor];
    }
    // Selected date
    else if([self isInDatesSelected:dayView.date]){
        dayView.circleView.hidden = NO;
        dayView.circleView.backgroundColor = [UIColor redColor];
        dayView.dotView.backgroundColor = [UIColor whiteColor];
        dayView.textLabel.textColor = [UIColor whiteColor];
    }
    // Other month
    else if(![_calendarManager.dateHelper date:_calendarContentView.date isTheSameMonthThan:dayView.date]){
        dayView.circleView.hidden = YES;
        dayView.dotView.backgroundColor = [UIColor redColor];
        dayView.textLabel.textColor = [UIColor lightGrayColor];
    }
    // Another day of the current month
    else{
        dayView.circleView.hidden = YES;
        dayView.dotView.backgroundColor = [UIColor redColor];
        dayView.textLabel.textColor = [UIColor blackColor];
    }
    if([self haveEventForDay:dayView.date]){
        if ([self haveEventForDay:[NSDate date]]&&[_calendarManager.dateHelper date:[NSDate date] isTheSameDayThan:dayView.date]) {
            dayView.circleView.hidden = NO;
            dayView.circleView.backgroundColor = todayColor;
            dayView.dotView.backgroundColor = [UIColor whiteColor];
            dayView.textLabel.textColor = [UIColor whiteColor];
        }else{
            dayView.circleView.hidden = NO;
            dayView.circleView.backgroundColor = greenbackgroundColor;
            dayView.dotView.backgroundColor = [UIColor whiteColor];
            dayView.textLabel.textColor = [UIColor whiteColor];
        }
    }
    else{
        dayView.dotView.hidden = YES;
    }
}
//日期自动刷新
- (void)calendar:(JTCalendarManager *)calendar prepareMenuItemView:(UILabel *)menuItemView date:(NSDate *)date
{
    static NSDateFormatter *dateFormatter;
    if(!dateFormatter){
        dateFormatter = [NSDateFormatter new];
        dateFormatter.dateFormat = @"yyyy年MMMM";
        
        dateFormatter.locale = _calendarManager.dateHelper.calendar.locale;
        dateFormatter.timeZone = _calendarManager.dateHelper.calendar.timeZone;
    }
    
    menuItemView.text = [dateFormatter stringFromDate:date];
}


#pragma mark - Date selection
//判断事件
- (BOOL)isInDatesSelected:(NSDate *)date
{
    for(NSDate *dateSelected in _datesSelected){
        //        if([_calendarManager.dateHelper date:dateSelected isTheSameDayThan:date]){
        //            return YES;
        //        }
        if ([dateSelected isEqualToDate:date]) {
            return YES;
        }
    }
    
    return NO;
}


#pragma mark - Fake data

// Used only to have a key for _eventsByDate
//日期格式设定
- (NSDateFormatter *)dateFormatter
{
    static NSDateFormatter *dateFormatter;
    if(!dateFormatter){
        dateFormatter = [NSDateFormatter new];
        dateFormatter.dateFormat = @"dd-MM-yyyy";
    }
    
    return dateFormatter;
}
//判断某日期是否签到
- (BOOL)haveEventForDay:(NSDate *)date
{
    NSString *key = [[self dateFormatter] stringFromDate:date];
    
    if(_eventsByDate[key] && [(NSArray*)_eventsByDate[key] count] > 0){
        return YES;
    }
    
    return NO;
    
}
//获取已签到日期并刷新日历
- (void)createEvents
{
    BmobQuery   *bquery = [BmobQuery queryWithClassName:@"sign"];
    
    [bquery whereKey:@"user_id" equalTo:[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"]];
    [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        NSLog(@"%@",error);
        for (BmobObject *obj in array) {
            // Generate 30 random dates between now and 60 days later
            NSLog(@"%@",[obj objectForKey:@"sign_date"]);
            NSDate *randomDate = [obj objectForKey:@"sign_date"];
            
            // Use the date as key for eventsByDate
            NSString *key = [[self dateFormatter] stringFromDate:randomDate];
            
            if(!_eventsByDate[key]){
                _eventsByDate[key] = [NSMutableArray new];
            }
            
            [_eventsByDate[key] addObject:randomDate];

        }
        [self removeLoading];
        
        self.calendarMenuView = [[JTCalendarMenuView alloc]initWithFrame:CGRectMake(0, 60, ScreenWidth, 30)];
        self.calendarContentView = [[JTHorizontalCalendarView alloc]initWithFrame:CGRectMake(0, 90, ScreenWidth, 300)];
        NSLog(@"%f",ScreenWidth);
        NSLog(@"%f",ScreenHeight);

        if ([self haveEventForDay:[NSDate date]]){
            UIBarButtonItem *locItem = self.toolbarItems[3];
            locItem.title = @"已签到";
            locItem.enabled = NO;
        }
        
        [self.view addSubview:_calendarMenuView];
        [self.view addSubview:_calendarContentView];
        [self.view addSubview:self.mapView];
        
        _calendarManager = [JTCalendarManager new];
        _calendarManager.delegate = self;
        
        [_calendarManager setMenuView:_calendarMenuView];
        [_calendarManager setContentView:_calendarContentView];
        [_calendarManager setDate:[NSDate date]];
        
        _datesSelected = [NSMutableArray new];
        _selectionMode = NO;
        
    }];
    
}
#pragma mark - 签到
//将签到信息发送到后台并刷新
-(void)submit{
    if ([sign_address isEqualToString:@""]) {
        DSToast *toast=[[DSToast alloc]initWithText:@"请定位"];
        [toast showInView:self.view];
        return;
    }
    UIBarButtonItem *locItem = self.toolbarItems[3];
    locItem.enabled = NO;
    
    BmobObject *obj = [[BmobObject alloc] initWithClassName:@"sign"];
    NSString *str=[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"];
    [obj setObject:str forKey:@"user_id"];
    
    [obj setObject:[NSDate date] forKey:@"sign_date"];
    
    [obj setObject:sign_address forKey:@"sign_address"];
    [obj setObject:sign_location forKey:@"sign_location"];

    //location.coordinate.latitude
    [obj saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
        NSLog(@"%@",error);
        if (!error) {
            NSLog(@"提交成功");
            
            locItem.title = @"已签到";
            locItem.enabled = NO;
            
            NSDate *currentDate = [NSDate date];
            NSString *key = [[self dateFormatter] stringFromDate:currentDate];
            if(!_eventsByDate[key]){
                _eventsByDate[key] = [NSMutableArray new];
            }
            [_eventsByDate[key] addObject:currentDate];
            
            NSLog(@"%@",_eventsByDate);
            [_calendarManager reload];
        }else{
            DSToast *toast=[[DSToast alloc]initWithText:[NSString stringWithFormat:@"%@",error]];
            [toast showInView:self.view];
            locItem.enabled = YES;
        }
        
    }];
}



#pragma mark - Action Handle
//下面为高德地图sdk接口API使用

- (void)configLocationManager
{
    self.locationManager = [[AMapLocationManager alloc] init];
    
    [self.locationManager setDelegate:self];
    
    //设置期望定位精度
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    
    //设置不允许系统暂停定位
    [self.locationManager setPausesLocationUpdatesAutomatically:NO];
    
    //设置允许在后台定位
    [self.locationManager setAllowsBackgroundLocationUpdates:YES];
    
    //设置定位超时时间
    [self.locationManager setLocationTimeout:DefaultLocationTimeout];
    
    //设置逆地理超时时间
    [self.locationManager setReGeocodeTimeout:DefaultReGeocodeTimeout];
    
    //设置开启虚拟定位风险监测，可以根据需要开启
    [self.locationManager setDetectRiskOfFakeLocation:NO];
}

- (void)cleanUpAction
{
    //停止定位
    [self.locationManager stopUpdatingLocation];
    
    [self.locationManager setDelegate:nil];
    
    [self.mapView removeAnnotations:self.mapView.annotations];
}

- (void)reGeocodeAction
{
    
    [self.mapView removeAnnotations:self.mapView.annotations];
    
    //进行单次带逆地理定位请求
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:self.completionBlock];
    
}

- (void)locAction
{
    [self.mapView removeAnnotations:self.mapView.annotations];
    
    //进行单次定位请求
    [self.locationManager requestLocationWithReGeocode:NO completionBlock:self.completionBlock];
}

#pragma mark - Initialization
//定位回调函数
- (void)initCompleteBlock
{
    __weak signViewController *weakSelf = self;
    self.completionBlock = ^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error)
    {
        if (error != nil && error.code == AMapLocationErrorLocateFailed)
        {
            //定位错误：此时location和regeocode没有返回值，不进行annotation的添加
            NSLog(@"定位错误:{%ld - %@};", (long)error.code, error.localizedDescription);
            return;
        }
        else if (error != nil
                 && (error.code == AMapLocationErrorReGeocodeFailed
                     || error.code == AMapLocationErrorTimeOut
                     || error.code == AMapLocationErrorCannotFindHost
                     || error.code == AMapLocationErrorBadURL
                     || error.code == AMapLocationErrorNotConnectedToInternet
                     || error.code == AMapLocationErrorCannotConnectToHost))
        {
            //逆地理错误：在带逆地理的单次定位中，逆地理过程可能发生错误，此时location有返回值，regeocode无返回值，进行annotation的添加
            NSLog(@"逆地理错误:{%ld - %@};", (long)error.code, error.localizedDescription);
        }
        else if (error != nil && error.code == AMapLocationErrorRiskOfFakeLocation)
        {
            //存在虚拟定位的风险：此时location和regeocode没有返回值，不进行annotation的添加
            NSLog(@"存在虚拟定位的风险:{%ld - %@};", (long)error.code, error.localizedDescription);
            return;
        }
        else
        {
            //没有错误：location有返回值，regeocode是否有返回值取决于是否进行逆地理操作，进行annotation的添加
            sign_address = regeocode.formattedAddress;
            sign_location = [NSString stringWithFormat:@"longitude:%.8f,latitude:%.8f",location.coordinate.longitude,location.coordinate.latitude];
            NSLog(@"%@",regeocode);
            NSLog(@"%@",location);
            NSLog(@"%.8f",location.coordinate.latitude);
            NSLog(@"%.8f",location.coordinate.longitude);
        }
        
        //根据定位信息，添加annotation
        MAPointAnnotation *annotation = [[MAPointAnnotation alloc] init];
        [annotation setCoordinate:location.coordinate];
        
        //有无逆地理信息，annotationView的标题显示的字段不一样
        if (regeocode)
        {
            [annotation setTitle:[NSString stringWithFormat:@"%@", regeocode.formattedAddress]];
            [annotation setSubtitle:[NSString stringWithFormat:@"%@-%@-%.2fm", regeocode.citycode, regeocode.adcode, location.horizontalAccuracy]];
        }
        else
        {
            [annotation setTitle:[NSString stringWithFormat:@"lat:%f;lon:%f;", location.coordinate.latitude, location.coordinate.longitude]];
            [annotation setSubtitle:[NSString stringWithFormat:@"accuracy:%.2fm", location.horizontalAccuracy]];
        }
        
        signViewController *strongSelf = weakSelf;
        [strongSelf addAnnotationToMapView:annotation];
    };
}

- (void)addAnnotationToMapView:(id<MAAnnotation>)annotation
{
    [self.mapView addAnnotation:annotation];
    
    [self.mapView selectAnnotation:annotation animated:YES];
    [self.mapView setZoomLevel:15.1 animated:NO];
    [self.mapView setCenterCoordinate:annotation.coordinate animated:YES];
}
//设置地图界面
- (void)initMapView
{
    if (self.mapView == nil)
    {
        self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 390, SCREENWIDTH, ScreenHeight-390-40)];
        [self.mapView setDelegate:self];
        
//        [self.view addSubview:self.mapView];
    }
}
//设置下层按钮
- (void)initToolBar
{
    UIBarButtonItem *flexble = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                             target:nil
                                                                             action:nil];
    
    UIBarButtonItem *reGeocodeItem = [[UIBarButtonItem alloc] initWithTitle:@"定位"
                                                                      style:UIBarButtonItemStylePlain
                                                                     target:self
                                                                     action:@selector(reGeocodeAction)];
    
    UIBarButtonItem *locItem = [[UIBarButtonItem alloc] initWithTitle:@"签到"
                                                                style:UIBarButtonItemStylePlain
                                                               target:self
                                                               action:@selector(submit)];
    //locAction
    
    
    self.toolbarItems = [NSArray arrayWithObjects:flexble, reGeocodeItem, flexble, locItem, flexble, nil];
}

- (void)initNavigationBar
{
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Clean"
                                                                              style:UIBarButtonItemStylePlain
                                                                             target:self
                                                                             action:@selector(cleanUpAction)];
}

#pragma mark - Life Cycle
//地图视图函数整合
- (void)MapDidLoad
{
    [self initToolBar];
    
    //[self initNavigationBar];
    
    [self initMapView];
    
    [self initCompleteBlock];
    
    [self configLocationManager];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    self.navigationController.toolbar.translucent   = YES;
    self.navigationController.toolbarHidden         = NO;
}

- (void)dealloc
{
    [self cleanUpAction];
    
    self.completionBlock = nil;
}

#pragma mark - MAMapView Delegate
//协议代理
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *pointReuseIndetifier = @"pointReuseIndetifier";
        
        MAPinAnnotationView *annotationView = (MAPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndetifier];
        }
        
        annotationView.canShowCallout   = YES;
        annotationView.animatesDrop     = YES;
        annotationView.draggable        = NO;
        annotationView.pinColor         = MAPinAnnotationColorPurple;
        
        return annotationView;
    }
    
    return nil;
}




@end


























